package avatar;

import java.sql.SQLException;
import java.util.Vector;

import javax.sql.rowset.CachedRowSet;

import com.game.majiang.Event.Time.TimeEvent;
import com.game.majiang.Event.Time.TimeListener;
import com.game.majiang.Event.Time.TimeManager;
import com.game.majiang.config.LogManager;
import com.game.server.db.SqlHelper;

public class avatarmanager implements TimeListener {
	public avatarmanager()
	{
		m_TimeManager = new TimeManager();
		m_TimeManager.addTimeListener(this);
	}
	public static avatarmanager Instance;
	public static avatarmanager getInstance()
	{
		if(Instance == null)
		{
			Instance = new avatarmanager();
		}
		return Instance;
	}
	public TimeManager m_TimeManager;
	public Vector<avatar> avatarspre = new Vector<avatar>();
	public Vector<avatar> avatars = new Vector<avatar>();
	public synchronized void InitAvatar()
	{
		String sql = "select id,account,passworld,nickname,topranking,roomid,difen from avatar";
		CachedRowSet rs = SqlHelper.getResultSet(sql);
		try {
			while (rs.next()) 
			{  
				int id  = rs.getInt(1);
				String account  = rs.getString(2);
				String passworld  = rs.getString(3);
				String nickname  = rs.getString(4);
				int power = rs.getInt(5);
				int roomid = rs.getInt(6);
				int difen = rs.getInt(7);
				avatar a = new avatar();
				a.id = id;
				a.account = account;
				a.passworld = passworld;
				a.nickname = nickname;
				a.power = power;
				a.roomid = roomid;
				a.difen = difen;
				avatarspre.add(a);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			LogManager.getInstance().Error("Sql:" + sql + "错误"+e);
		}
	}
	public avatar Findavatar(int id)
	{
		for(int i=0; i<avatars.size(); i++)
		{
			if(avatars.get(i).uid == id)
			{
				return avatars.get(i);
			}
		}
		return null;
	}
	public void FindAccavatar(String acc, String key, int value)
	{
		for(int i=0; i<avatars.size(); i++)
		{
			if(avatars.get(i).account.equals(acc))
			{
				if ("topranking".equals(key)) {
					avatars.get(i).power = value;
				} else if("roomid".equals(key)) {
					avatars.get(i).roomid = value;
				}else if("difen".equals(key)) {
					avatars.get(i).difen = value;
				}
				
				break;
			}
		}
		
	}
	public Vector<avatar> Getavatars()
	{
		return avatars;
	}
	@Override
	public void timeEvent(TimeEvent event) {
		// TODO Auto-generated method stub
		addListener();
	}
	public synchronized void addListener()
	{
		for(int i=0; i<avatarspre.size(); i++)
		{
			avatars.add(avatarspre.get(i));
			avatarspre.remove(i);
			break;
		}
		for(int i=0; i<avatars.size(); i++)
		{
			avatars.get(i).timeEvent();
		}
	}
}
